<?php

namespace api\modules\app\controllers;

use api\components\BaseController;
use api\modules\app\models\QrcodeRecord;
use api\modules\app\services\QrcodeService;
use api\utils\StringUtil;
use app\components\Job;
use Yii;

class QrcodeRecordController extends BaseController
{
    public $modelClass = 'api\\modules\\app\\models\\QrcodeRecord';

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create']);

        return $actions;
    }

    public function actionIndex()
    {
        $params = $this->getQuery();

        return (new QrcodeService())->searchBatch($params);
    }

    public function actionCreate()
    {
        $params = $this->getParams();
        $count = $params['count'] ?? 1;
        $user = ['id' => 1, 'username' => 'admin'];
        // $user = $this->getUser();
        $batch = new QrcodeRecord([
            'count' => $count,
            //1,2
//            'tag_code' => isset($params['tag_code']) ? $params['tag_code'] : '',
//            'tag_name' => isset($params['tag_name']) ? $params['tag_name'] : '',
            'user_id' => $user['id'],
            'user_name' => $user['username'],
        ]);
        $batch->save();
        $batchCode = $batch->id;
//        $batch->path = QrcodeService::batchCreate($count, $batchCode, $params['needImage'] ?? true);
        $batch->path = QrcodeService::batchCreate($batch, $params);
        $batch->save();
        // $this->genQrcode($batchCode);

        return $batch;
    }

    /**
     * push job 队列
     */
    private function genQrcode($batchCode)
    {
        $class = 'App\\Job\\GenQrcode';
        $args = [
            'batchCode' => $batchCode,
        ];
        (new Job())->create($class, $args);
    }
}